import {IMainApp} from "../../types";

/**
 * @method getHistoryModeActiveRule
 * @description 主应用工程环境下 history 模式主应用注册微应用时激活路由计算方法
 * @param routerPrefix
 * */
export const getHistoryModeActiveRule = (routerPrefix = "") => {
    return (location: { pathname: string }) => location.pathname.startsWith(`${routerPrefix}`);
};
/**
 * @method getHistoryModeActiveRule
 * @description 主应用工程环境下 hash 模式主应用注册微应用时激活路由计算方法
 * @param hash
 * */
export const getHashModeActiveRule = (hash: any) => (location: any) => location.hash.startsWith(hash);

/**
 * @method getMicroAppActiveRuleByRouteMode
 * @description 主应用工程环境下 根据当前路由模式计算注册微应用的激活路由
 * @param routeMode
 * @param microApps
 * */
export const getMicroAppActiveRuleByRouteMode = (
    routeMode = "hash",
    microApps = []
) => {
    if (microApps && microApps.length) {
        microApps.forEach((app: any) => {
            if (app && app.activeRule) {
                if (routeMode === "history") {
                    app.activeRule = getHistoryModeActiveRule(app.activeRule);
                }
                if (routeMode === "hash") {
                    if (!app.activeRule.includes("#")) {
                        app.activeRule = `#${app.activeRule}`;
                    }
                    app.activeRule = getHashModeActiveRule(app.activeRule);
                }
            }
        });
    }
    return microApps;
};

/**
 * @method addMicroRoutesToMainRoute
 * @description 主应用工程环境下 添加子路由到主应用路由里面
 * @param parentPath
 * @param mainRoutes
 * @param childrenRoutes
 * */
export function addMicroRoutesToMainRoute(
    parentPath = "",
    mainRoutes: any,
    childrenRoutes: any
) {
    if (mainRoutes && mainRoutes.length) {
        mainRoutes.forEach((route: any) => {
            if (route.path === parentPath) {
                if (childrenRoutes && childrenRoutes.length) {
                    if (parentPath !== "/") {
                        childrenRoutes.forEach((child: any) => {
                            child.path = `${parentPath}${child.path}`;
                        });
                    }
                    route.children.push(...childrenRoutes);
                }
            }
            if (route.children && route.children.length) {
                addMicroRoutesToMainRoute(parentPath, route.children, childrenRoutes);
            }
        });
    }
    return mainRoutes;
}

export const MainApp: IMainApp = {
    getHistoryModeActiveRule,
    getHashModeActiveRule,
    getMicroAppActiveRuleByRouteMode,
    addMicroRoutesToMainRoute
}
